<template>
  <div>
    <div class="table-operator">
      <a-button
        type="primary"
        icon="plus"
        :loading="btnLoading"
        @click="handleAddVisible(true)"
        :disabled="$store.state.user.project && $store.state.user.project.status === 3"
        v-if="editable"
      >
        {{ $t('all.autotext1290') }}
      </a-button>
    </div>
    <div class="table">
      <a-table
        :data-source="data"
        bordered
        size="middle"
        :rowKey="record=>record.id"
      >
        <a-table-column key="roleId" :title="$t('all.autotext334')" align="center" >
          <template slot-scope="text, record, index">
            <span>{{ index + 1 }}</span>
          </template>
        </a-table-column>
        <a-table-column
          key="name"
          :title="$t('all.autotext128')"
          data-index="name"
          align="center"
        />
        <a-table-column
          key="code"
          :title="$t('all.autotext1524')"
          data-index="code"
          align="center"
        />
        <a-table-column
          key="description"
          :title="$t('all.autotext273')"
          data-index="description"
          align="center"
        />
        <a-table-column key="status" :title="$t('all.autotext175')" align="center">
          <template slot-scope="text, record">
            {{ isEnabledStatus(record) ? $t('all.autotext307') : $t('all.autotext567') }}
          </template>
        </a-table-column>
        <a-table-column key="action" :title="$t('all.autotext187')" align="center">
          <template slot-scope="text, record">
            <span>
              <a-space>
                <a @click="editRow(record, false)">{{ $t('all.autotext568') }}</a>
                <a
                  @click="editRow(record, true)"
                  v-if="!($store.state.user.project &&  $store.state.user.project.status===3) && editable"
                >{{ $t('all.autotext919') }}</a>
                <a
                  v-if="!($store.state.user.project && $store.state.user.project.status===3) && editable"
                  @click="updateRoleStatus(record)"
                >{{ +record.status === 1 ? $t('all.autotext567') : $t('all.autotext307') }}
                </a>
              </a-space>
              <!--<a-divider-->
              <!--  type="vertical"-->
              <!--  v-if="record.code !== 'PROJECT_ADMIN' && !($store.state.user.project &&  $store.state.user.project.status===3) && editable"-->
              <!--/>-->
              <!--<a-popconfirm-->
              <!--  title="确定删除本条数据吗?"-->
              <!--  ok-text="确定"-->
              <!--  cancel-text="取消"-->
              <!--  @confirm="deleteRow(record)"-->
              <!--&gt;-->
              <!--  <a v-if="record.code !== 'PROJECT_ADMIN' && !($store.state.user.project &&  $store.state.user.project.status===3) && editable">删除</a>-->
              <!--</a-popconfirm>-->
            </span>
          </template>
        </a-table-column>
      </a-table>
    </div>
    <!-- <TreeModel
      :visible="addVisible"
      :permission="permission"
      :permissionMP="permissionMP"
      title="新增角色"
      @ok="handconfirm"
      @cancel="addVisible = false"
    /> -->
    <AddRoleNewDrawer
      :visible="addVisible"
      :permission="permission"
      :permissionCRA="permissionCRA"
      :permissionMP="permissionMP"
      :configId="configId"
      @ok="handconfirm"
      @cancel="addVisible = false"
    />
    <EditRoleNewDrawer
      v-if="editVisible"
      :record="rowRecord"
      ref="treeEdit"
      :visible="editVisible"
      :permission="permission"
      :permissionCRA="permissionCRA"
      :permissionMP="permissionMP"
      :rolePermission="rolePermission"
      :rolePermissionMP="rolePermissionMP"
      :is-edit="isEdit"
      :title="$t('all.autotext1184')"
      @ok="editVisible = false"
      @cancel="editOk()"
    />
    <!-- <TreeModelEdit
      v-if="editVisible"
      :record="rowRecord"
      ref="treeEdit"
      :visible="editVisible"
      :permission="permission"
      :permissionMP="permissionMP"
      :rolePermission="rolePermission"
      :rolePermissionMP="rolePermissionMP"
      title="编辑角色"
      @ok="editVisible = false"
      @cancel="editOk()"
    /> -->
  </div>
</template>

<script>
import { CURRENT_PERMISSION, CURRENT_ROLE } from '@/store/mutation-types'
import AddRoleNewDrawer from './role/addRoleNewDrawer.vue'
import EditRoleNewDrawer from './role/editRoleNewDrawer.vue'
import { permissionList, permissionListByPro } from '@/api/project/configItem/pms.js'
import { getRoleList, userRole, delRole, getRoleListByPro, userRoleByPro, delRoleByPro, apiUpdateProRoleStatus } from '@/api/project/configItem/role.js'
import _ from 'lodash'

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows)
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows)
  }
}
export default {
  props: {
    editable: {
      type: Boolean,
      default: false
    }
  },
  components: {
    AddRoleNewDrawer,
    EditRoleNewDrawer
  },
  data () {
    return {
      data: [],
      rowRecord: {},
      permission: [],
      permissionCRA: [],
      permissionMP: [],
      permissionSub: [],
      addVisible: false,
      editVisible: false,
      rolePermission: [], // 当前角色拥有的权限
      rolePermissionMP: [],
      rolePermissionSUB: [],
      rowSelection,
      loading: false,
      expandedRowKeys: [],
      publicPermission: [],
      publicPermissionCRA: [],
      publicPermissionMP: [],
      publicPermissionSUB: [],
      isEdit: false,
      configId: '',
      btnLoading: true
    }
  },
  created () {
    this.configId = this.$route.query.configId
  },
  mounted () {
    this.fetchPermissionList()
    this.fetchList()
  },
  activated () {
    this.fetchList()
  },
  methods: {
    refreshListData () {
      this.fetchPermissionList()
    },
    editOk () {
      this.editVisible = false
      this.fetchList()
    },
    // 获取列表信息
    fetchList (params = {}) {
      if (this.$store.getters.project != null) {
        getRoleListByPro({
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
          configId: this.configId
        }).then(res => {
          this.data = res
        })
      } else {
        getRoleList().then(res => {
          this.data = res
        })
      }
    },
    // 遍历加参数字段
    setPmsParams (permission) {
      if (permission && permission.length) {
        permission.forEach(item => {
          item.isExpand = false
          item.checked = false
          if (item.child && item.child.length) {
            item.child.forEach(item1 => {
              item1.checked = false
            })
          }
          if (item.children) {
            this.setPmsParams(item.children)
          }
        })
      }
    },
    // 获取权限列表
    fetchPermissionList () {
      if (this.$store.getters.project != null) {
        permissionListByPro({
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
          configId: this.configId
        }).then(res => {
          this.permission = res
          this.setPmsParams(this.permission)
          this.publicPermission = []
          this.permission.map(item => {
            // epv1.5 不可编辑权限由 getPms 接口返回
            // 公共权限不可编辑 (最多三级)
            // item.disabled = item.isPublic === 1
            // if (item.disabled) {
            //   this.publicPermission.push(item.id)
            // }
            // if (item.children != null) {
            //   item.children.map(sub => {
            //     sub.disabled = sub.isPublic === 1
            //     if (sub.disabled) {
            //       this.publicPermission.push(sub.id)
            //     }
            //     if (sub.children != null) {
            //       sub.children.map(child => {
            //         child.disabled = child.isPublic === 1
            //         if (child.disabled) {
            //           this.publicPermission.push(child.id)
            //         }
            //       })
            //     }
            //   })
            // }
          })
          // console.log('========', this.permission)
        })


        // CRA PC端权限树
        permissionListByPro({
          proId: this.$store.getters.project.id,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
          roleCode: 'CRA',
          configId: this.configId
        }).then(res => {
          this.permissionCRA = res
          this.setPmsParams(this.permissionCRA)
          this.publicPermissionCRA = []
          this.permissionCRA.map(item => {
            // epv1.5 不可编辑权限由 getPms 接口返回
            // 公共权限不可编辑 (最多三级)
            // item.disabled = item.isPublic === 1
            // if (item.disabled) {
            //   this.publicPermissionCRA.push(item.id)
            // }
            // if (item.children != null) {
            //   item.children.map(sub => {
            //     sub.disabled = sub.isPublic === 1
            //     if (sub.disabled) {
            //       this.publicPermissionCRA.push(sub.id)
            //     }
            //     if (sub.children != null) {
            //       sub.children.map(child => {
            //         child.disabled = child.isPublic === 1
            //         if (child.disabled) {
            //           this.publicPermissionCRA.push(child.id)
            //         }
            //       })
            //     }
            //   })
            // }
          })
          // console.log('this.publicPermissionCRA', this.publicPermissionCRA)
        })


        permissionListByPro({
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.MP.value,
          configId: this.configId
        }).then(res => {
          // 研究者
          this.permissionMP = JSON.parse(JSON.stringify(res))
          this.setPmsParams(this.permissionMP)
          this.publicPermissionMP = []
          this.permissionMP.map(item => {
            // epv1.5 不可编辑权限由 getPms 接口返回
            // 公共权限不可编辑 (最多三级)
            // item.disabled = item.isPublic === 1
            // if (item.disabled) {
            //   this.publicPermissionMP.push(item.id)
            // }
            // if (item.children != null) {
            //   item.children.map(sub => {
            //     sub.disabled = sub.isPublic === 1
            //     if (sub.disabled) {
            //       this.publicPermissionMP.push(sub.id)
            //     }
            //     if (sub.children != null) {
            //       sub.children.map(child => {
            //         child.disabled = child.isPublic === 1
            //         if (child.disabled) {
            //           this.publicPermissionMP.push(child.id)
            //         }
            //       })
            //     }
            //   })
            // }
          })
          console.log('========MP', this.permissionMP)

          // 受试者
          this.permissionSUB = JSON.parse(JSON.stringify(res))
          this.setPmsParams(this.permissionSUB)
          this.publicPermissionSUB = []
          this.permissionSUB.map(item => {
            // 公共权限不可编辑 (最多三级)
            // item.disabled = true
            // // if (item.disabled) {
            // //   this.publicPermissionSUB.push(item.id)
            // // }
            // if (item.children != null) {
            //   item.children.map(sub => {
            //     sub.disabled = true
            //     // if (sub.disabled) {
            //     //   this.publicPermissionSUB.push(sub.id)
            //     // }
            //     if (sub.child != null) {
            //       sub.child.map(child => {
            //         child.disabled = true
            //         // if (child.disabled) {
            //         //   this.publicPermissionSUB.push(child.id)
            //         // }
            //       })
            //     }
            //   })
            // }
          })
          // console.log('========MP', this.permissionMP)
        }).finally(() => {
          this.btnLoading = false
        })
      } else {
        permissionList().then(res => {
          this.permission = res
          this.setPmsParams(this.permission)
          this.publicPermission = []
          this.permission.map(item => {
            // epv1.5 不可编辑权限由 getPms 接口返回
            // 公共权限不可编辑 (最多三级)
            // item.disabled = item.isPublic === 1
            // if (item.disabled) {
            //   this.publicPermission.push(item.id)
            // }
            // if (item.children != null) {
            //   item.children.map(sub => {
            //     sub.disabled = sub.isPublic === 1
            //     if (sub.disabled) {
            //       this.publicPermission.push(sub.id)
            //     }
            //     if (sub.children != null) {
            //       sub.children.map(child => {
            //         child.disabled = child.isPublic === 1
            //         if (child.disabled) {
            //           this.publicPermission.push(child.id)
            //         }
            //       })
            //     }
            //   })
            // }
          })
          // console.log('========', this.permission)
        }).finally(() => {
          this.btnLoading = false
        })
      }
    },
    // 确定处理
    handconfirm (value) {
      this.addVisible = false
      this.fetchList()
    },
    handleAddVisible (flag = false) {
      this.setPmsParams(this.permission)
      this.setPmsParams(this.permissionCRA)
      this.setPmsParams(this.permissionMP)
      this.setPmsParams(this.permissionSUB)
      // this.addVisible = flag
      this.$store.commit(CURRENT_PERMISSION, {
        permission: this.permission,
        permissionCRA: this.permissionCRA,
        permissionMP: this.permissionMP,
        permissionSUB: this.permissionSUB
      })
      this.$router.push({ path: '/overview/config/addRole', query: { configId: this.configId } })
    },
    addPermission (row) {
      console.log(row)
    },
    recurser (target, dataSource, stand) {
      dataSource.forEach(item => {
        if (stand.findIndex(i => i === item.id) >= 0) {
          target.push(item.id)
        }
        if (item.child && item.child.length) {
          item.child.forEach(item1 => {
            if (stand.findIndex(i => i === item1.id) >= 0) {
              target.push(item1.id)
            }
          })
        }
        if (item.children != null && item.children.length > 0) {
          this.recurser(target, item.children, stand)
        }
      })
    },
    isEnabledStatus ({ status }) {
      return +status === 1
    },
    updateRoleStatus ({ status, id }) {
      const isEnabledStatus = +status === 1
      let toggleStatus = 1
      if (isEnabledStatus) {
        toggleStatus = 0 // 0-禁用 1-启用
      }
      const params = {
        id,
        configId: this.configId,
        proId: this.$store.getters.project.id,
        status: toggleStatus
      }
      return apiUpdateProRoleStatus(params).then(res => {
        this.$message.success(this.$t('all.autotext470'))
        this.fetchList()
      })
    },
    // 编辑角色
    editRow (row, flag) {
      this.isEdit = flag
      // debugger
      if (this.$store.getters.project != null) {
        userRoleByPro({
          roleId: row.id,
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
          configId: this.configId
        }).then(res => {
          const { checkList, isPublicList } = res
          const list = []
          checkList.forEach(element => {
            list.push(element.pmsId)
          })
          let plist = []
          if (row.code === 'CRA') {
            this.recurser(plist, this.permissionCRA, list)
          } else {
            this.recurser(plist, this.permission, list)
          }

          const plistMP = []
          this.recurser(plistMP, this.permissionMP, list)

          const plistSUB = []
          this.recurser(plistSUB, this.permissionSUB, list)

          if (row.code === 'CRA') {
            this.rolePermission = _.uniq([...this.publicPermissionCRA, ...plist]) // 该用户拥有的权限
          } else {
            this.rolePermission = _.uniq([...this.publicPermission, ...plist]) // 该用户拥有的权限
          }

          this.rolePermissionMP = row.code === 'Subjects' ? _.uniq([...this.publicPermissionSUB, ...plistSUB]) : _.uniq([...this.publicPermissionMP, ...plistMP]) // 该用户拥有的权限

          // console.log('======123123=====', this.rolePermissionMP)
          // this.rowRecord = row
          // this.editVisible = true // 获取到后在弹出
          this.toEdit({
            disablePermissionList: isPublicList,
            rolePermission: this.rolePermission,
            rolePermissionMP: this.rolePermissionMP,
            isEdit: flag
          }, row)
        })
      } else {
        userRole({
          roleId: row.id,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
        }).then(res => {
          const { checkList, isPublicList } = res
          const list = []
          checkList.forEach(element => {
            list.push(element.pmsId)
          })
          this.rolePermission = _.uniq([...this.publicPermission, ...list]) // 该用户拥有的权限
          // this.rowRecord = row
          // this.editVisible = true // 获取到后在弹出
          this.toEdit({
            disablePermissionList: isPublicList,
            rolePermission: this.rolePermission,
            isEdit: flag
          }, row)
        })
      }
    },
    // 跳转到编辑页面
    toEdit (mData, row, flag) {
      this.$store.commit(CURRENT_PERMISSION, {
        permission: this.permission,
        permissionCRA: this.permissionCRA,
        permissionMP: row.code === 'Subjects' ? this.permissionSUB : this.permissionMP,
        ...mData
      })
      this.$store.commit(CURRENT_ROLE, row)
      this.$router.push({ path: '/overview/config/editRole', query: { configId: this.configId } })
    },
    // 删除事件
    deleteRow (row) {
      const id = row.id
      if (this.$store.getters.project != null) {
        delRoleByPro({
          id,
          proId: this.$store.getters.project.id,
          code: row.code,
          description: row.description,
          name: row.name,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
          configId: this.configId
        }).then(res => {
          this.$message.success(this.$t('all.autotext1455'))
          this.fetchList()
        })
      } else {
        delRole({
          id
        }).then(res => {
          this.$message.success(this.$t('all.autotext1455'))
          this.fetchList()
        })
      }
    }
  }
}
</script>

<style></style>
